
package ma.crawler.mplayer.sogou.parser;

import android.text.TextUtils;

import ma.crawler.mplayer.sogou.model.SogouMusicInfo;
import ma.crawler.mplayer.sogou.provider.SogouClient;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SogouMusicParser {

    private static final Pattern MUSIC_PATTERN = Pattern
            .compile("class=\"cbbox\"[\\s\\S]*?class=\"songname\"[\\s\\S]*?\\stitle=\"([^\"]*)\"[\\s\\S]*?class=\"singger\"[\\s\\S]*?\\stitle=\"([^\"]*)\"[\\s\\S]*?class=\"singger\"[\\s\\S]*?\\stitle=\"([^\"]*)\"[\\s\\S]*?class=\"cd3\"[\\s\\S]*?onclick=\"window.open\\(([^\\)]*)\\)[\\s\\S]*?<td nowrap>([^<]*)<[\\s\\S]*?<td>([^<]*)</td>[\\s\\S]*?\\\"spdbar(\\d+)\\\">");

    private static final Pattern DOWNLOAD_URL_PATTERN = Pattern
            .compile("class=\"dl\"><a href=\\\"([^\"]*)\"");

    public static List<SogouMusicInfo> parse(String html) {
        final List<SogouMusicInfo> list = new ArrayList<SogouMusicInfo>(30);
        final Matcher matcher = MUSIC_PATTERN.matcher(html);
        while (matcher.find()) {
            SogouMusicInfo music = new SogouMusicInfo();
            music.mName = matcher.group(1);
            music.mArtist = matcher.group(2);
            music.mAlbum = matcher.group(3);
            String linkText = matcher.group(4);
            music.mLink = getLink(linkText);
            music.mSize = matcher.group(5);
            music.mType = matcher.group(6);
            music.mSpeed = matcher.group(7);
            list.add(music);
        }
        return list;
    }

    private static String getLink(String linkText) {
        if (TextUtils.isEmpty(linkText)) {
            return null;
        }
        String[] array = linkText.split(",");
        String url = array[0].replaceAll("'", "");
        return SogouClient.getDownloadPage(url);
    }

    public static String parseDownloadUrl(String html) {
        if (TextUtils.isEmpty(html)) {
            return null;
        }
        final Matcher matcher = DOWNLOAD_URL_PATTERN.matcher(html);
        if (matcher.find()) {
            String link = matcher.group(1);
            return link;
        }
        return null;
    }
}
